<?php
/**
 *类自动/手动加载
 * 
 * @package Bic
 * @author Bic
 * @version $Id: load.php 2009年12月14日 21时41分19秒
 * @copyright (c) 2009 Bic
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 *
 * Minimum Requirement: PHP 5.x
 */
if (! defined ( 'IN_BIC' )) {
	die ( '非法加载来源!' );
}
class Bic_Core_Load extends Bic_Base {
	
	protected static $_extensions = null;

	private static $_instance = null;

	private function __construct(){
		spl_autoload_register(null,false);
		spl_autoload_extensions($this->_extensions);
	}
	
	static function getInstance($extensions='.php,.inc,.class,.interface'){
		if(''==$extensions){
			$extensions='.php,.inc,.class,.interface';
		}
		if (!(self::$_instance instanceof self)){
			self::$_instance = new self();
		    self::$_instance->set('_extensions',$extensions);
		    self::$_instance->register('Bic_Core_Load::defaultIncludeFunction');
		}
		return self::$_instance;
		
	}
	
	/**
	 * 系统自带框架加载函数
	 * @param string $className		类名
	 * @param string $extension		自定义扩展。默认为null，当设定值后，不搜索其他扩展！多个扩展，可用逗号“,”分割
	 */
	private static function defaultIncludeFunction($className,$extension=null){
        if(!class_exists($className)){
            $name = strtolower($className);
            if(!empty($extension)){
                $extensions=explode(',',$extension);
            }else{
                $extensions=explode(',',self::$_instance->get('_extensions'));
            }
            foreach($extensions as $extKey=>$extVal){
                if(strpos($extVal,'.') === false){
                    $extVal='.'.$extVal;
                }
                switch (substr($name, 0, strpos($name, '_'))){
                    case 'model':
                    case 'controller':
                        $file = APP_DIR.str_replace('_',DS,$name).$extVal;
                        break;
                    default:
                        $file = ROOT.str_replace('_',DS,$name).$extVal;
                        break;
                }
                if(file_exists($file)){
                    require_once $file;
                    break;
                }else{
                    return null;
                    throw new Bic_Exception("实例化类出错!<br />\n系统并未加载或定义此类：{$name}");
                }
            }
        }
	    
	}
	
	/**
	 * 扩展类型
	 * @param string $extensions
	 */
	public function extensions($extensions){
		spl_autoload_extensions($extensions);
	}
	public function register($loader){
		spl_autoload_register($loader,false);
	}
	public function unregister($loader){
		spl_autoload_unregister($loader);
	}
	private function __clone(){}
}